//秒表对象
function now(){
	return new Date().getTime();
}
function extend(obj, data){
	for (var k in data) {
		Object.defineProperty(obj, k, {value: data[k]});
	}
}
function Stopwatch(){
	if(!(this instanceof Stopwatch)) return new Stopwatch();
	this.log_arr = [];
	this.timeout_arr = [];
	this.duration = 0;
	this.startMs = 0;
}
extend(Stopwatch.prototype, {
	valueOf: function(){
		return this.startMs ? (now() - this.startMs + this.duration) : this.duration;
	},
	start: function(){
		if(this.startMs) return this;
		this.startMs = now();
		//添加timeout
		for (var i = 0; i < this.timeout_arr.length;) {
			var row = this.timeout_arr[i];
			if(row.time <= this.duration) {
				this.timeout_arr.splice(i, 1);
			}else{
				row.th = setTimeout(row.callback, row.time-this.duration);
				i++;
			}
		}
		return this;
	},
	pause: function(){
		if(!this.startMs) return this;
		this.duration += now() - this.startMs;
		this.startMs = 0;
		//移除timeout
		for (var i = 0; i < this.timeout_arr.length;) {
			var row = this.timeout_arr[i];
			if(row.time <= this.duration) {
				this.timeout_arr.splice(i, 1);
			}else{
				clearTimeout(row.th);
				i++;
			}
		}
		return this;
	},
	stop: function(){
		this.log_arr = [];
		//移除timeout
		for (;this.timeout_arr.length;) {
			var row = this.timeout_arr[0];
			clearTimeout(row.th);
			this.timeout_arr.splice(0, 1);
		}
		this.duration = 0;
		this.startMs = 0;
		return this;
	},
	log: function(){
		this.log_arr.push(this*1);
		return this;
	},
	setTimeout: function(callback, time){
		var timeout = {
			time : this+time,
			callback: callback
		}
		if(this.startMs) timeout.th = setTimeout(callback, time);
		this.timeout_arr.push(timeout);
		return timeout;
	},
	clearTimeout: function(timeout){
		var i = this.timeout_arr.indexOf(timeout);
		if(i==-1) return false;
		if(this.startMs) clearTimeout(timeout.th);
		this.timeout_arr.splice(i, 1);
		return true;
	}
})

export default Stopwatch;
